﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Yyyg.WebUI
{
    public static class Tools
    {
        /// <summary>
        /// 获取所有的错误信息
        /// </summary>
        /// <param name="mod"></param>
        /// <returns></returns>
        public static List<string> GetErrors(this ModelStateDictionary mod)
        {
            var res = new List<string>();
            //获取所有错误的Key
            List<string> Keys = mod.Keys.ToList();
            //获取每一个key对应的ModelStateDictionary
            foreach (var key in Keys)
            {
                var errors = mod[key].Errors.ToList();
                //将错误描述输出到控制台
                foreach (var error in errors)
                {
                    res.Add(error.ErrorMessage);
                }
            }
            return res;
        }

        /// <summary>
        /// 将手机号中间数字加密
        /// </summary>
        /// <param name="mob"></param>
        /// <returns></returns>
        public static string MobEncrypt(string mob)
        {
            if (mob.Length != 11) throw new ApplicationException("手机号码格式不合法");
            mob = mob.Remove(3, 5);
            return mob.Insert(3, "*****");
        }

        /// <summary>
        /// 随机数种子
        /// </summary>
        /// <returns></returns>
        public static int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }

        /// <summary>
        /// 获取随机Int32正整数值
        /// </summary>
        /// <returns></returns>
        public static int GetRandMax()
        {
            return new Random().Next(0, int.MaxValue);
        }

        /// <summary>
        /// 获取百分比
        /// </summary>
        /// <param name="value">当前值</param>
        /// <param name="sum">总值</param>
        /// <param name="fix">保留小数位数</param>
        /// <returns></returns>
        public static double CalcPercentage(double value, double sum, int fix = 2)
        {
            return Math.Round(value / sum * 100, fix);
        }
    }
}